package com.snda.lib.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.StringWriter;
import java.io.UnsupportedEncodingException;

/** * @author Chen.Zhidong * */

public class StreamHelper {

	/**
	 * InputStream转String 这里用的方法和下面一个函数方法不同，看官看到下面的函数自然会明白
	 * 
	 * @param is
	 *            * @param encode
	 * @return
	 */
	public static String stream2String(InputStream is, String strEncoding) {

		if (is != null) {
			try {
				InputStreamReader isReader = new InputStreamReader(is,
						strEncoding);
				BufferedReader bufferedReader = new BufferedReader(isReader);

				int i = -1;
				char[] arrayOfChar = new char[1024];
				StringWriter stringWrite = new StringWriter();
				while ((i = bufferedReader.read(arrayOfChar)) != -1) {
					stringWrite.write(arrayOfChar, 0, i);
				}

				is.close();
				return stringWrite.toString();
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return "";
	}

	public static String stream2String(InputStream is) {
		return stream2String(is, "UTF-8");
	}
}
